package com.tcm.doctor.web.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.base.core.exception.ServiceException;
import com.base.core.utils.R;
import com.tcm.doctor.domain.dto.DoctorDTO;
import com.tcm.doctor.domain.enums.Const;
import com.tcm.doctor.domain.enums.SexEnum;
import com.tcm.doctor.domain.vo.DoctorVO;
import com.tcm.doctor.service.DoctorService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/doctor")
@RestController
public class DoctorController {

    @DubboReference(version = "0.0.1-alpha", timeout = 6000, check = false, retries = 3)
    private DoctorService doctorService;

    @GetMapping("/view")
    public R view(@RequestParam("userId") Long userId) {
       return R.success(doctorService.findDoctorVerifyByUserId(userId));
    }

    @PostMapping("/save")
    public R create(@RequestBody DoctorDTO doctor) {
        try{
            doctorService.saveDoctor(doctor);
        }catch (ServiceException e){
            return R.fail(e.getResult().getCode(), e.getMessage());
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
        return R.success();
    }

    /**
     * 获取用户信息
     *
     * @param token
     * @return
     */
    @GetMapping("/parse/token")
    public R parseToken(@RequestParam("token") String token) {

        try {
            DoctorDTO userDTO = doctorService.findDoctorByToken(token);
            if(ObjectUtil.isEmpty(userDTO)){
                return R.fail("用户信息不存在");
            }
            DoctorVO userVO = new DoctorVO();
            BeanUtil.copyProperties(userDTO, userVO);
            if (ObjectUtil.isNotEmpty(userDTO.getAvatar())) {
                userVO.setAvatar(Const.MEDIA_URL + userDTO.getAvatar());
            }
            if(ObjectUtil.isNotEmpty(userDTO.getSex())){
                userVO.setSexText(SexEnum.getDesc(userDTO.getSex().toString()));
            }
            return R.success(userVO);
        } catch (ServiceException e) {
            return R.fail(e.getResult().getCode(), e.getMessage());
        }catch (Exception e){
            return R.fail(e.getMessage());
        }

    }
}

